package com.apop.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * @program: startech-shop-parent
 * @description: 跨域配置
 * @author: zjy
 * @create: 2020-07-27 06:16
 */
@Configuration
public class CorsConfig {

    private CorsConfiguration corsConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 发出跨域请求的地址 * 表示通配
        corsConfiguration.addAllowedOrigin("*");
        //corsConfiguration.addAllowedOrigin("https://blog.csdn.net");
        //  跨域的请求头
        corsConfiguration.addAllowedHeader("*");
        //  跨域的请求方法
        corsConfiguration.addAllowedMethod("*");
        //最终的结果是可以 在跨域请求的时候获取同一个 session
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        //配置 允许跨域访问的路由 /** 所有
        source.registerCorsConfiguration("/**", corsConfig());
        // 只允许 /demo/info 跨域
        //source.registerCorsConfiguration("/demo/info", corsConfig());
        return new CorsFilter(source);
    }

}
